<template>
  <div>
    <div
      :style="{
        borderTop: '0px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'left'
      }"
    ></div>
    <!-- :onRowSelectChange="columns => (this.selectColumns = columns)" -->
    <el-row :gutter="24">
      <el-col :span="24">
        <BreakSpace label="基本信息" :containerStyle="{ marginBottom: '10px' }"></BreakSpace>
        <div class="grid-content bg-purple">
          <FormPanel ref="formPanel" :list="formList" :cols="5" :labelWidth="110" :isSubmitBtn="false" />
          <FormPanel ref="formPanel1" :list="formList1" :cols="4" :labelWidth="110" :isSubmitBtn="false" />
        </div>
      </el-col>
    </el-row>
    <BreakSpace label="库存列表" :containerStyle="{ marginBottom: '10px' }"></BreakSpace>
    <FilterTable
      ref="basetablewas"
      columnsRef="partInventoryManagerInventoryManagerIndex"
      :fetchapi="fetchApi"
      :columns="columns"
      :params="fetchParams"
      :onSyncTableData="tablechangeFun"
      :datakey="'rows'"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="handleTableSelectChange"
      :defaultSelections="selectedRow"
      :onPageChange="handleTablePageChange"
      :dataSource="data"
    >
      <!-- selectionType="single" -->
      <template slot="controls">
        <el-button type="primary" icon="el-icon-plus" @click="addFun">新增库存</el-button>
      </template>
    </FilterTable>
    <!-- <br /> -->
    <!-- 为保证前端ui规范隐藏下方展示表单 -- hxj 2019/12/23 -->
    <BaseDialog title="配件库存新增" :visible.sync="addVisible" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <addStock :Fdata="FrowData" @close="closeHandle" @addChange="addChange" />
    </BaseDialog>
    <BaseDialog title="配件库存编辑" :visible.sync="emitVisible" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <emitStock :getdata="setEmitdata" @close="emitCloseHandle" @addChange="emitChange" />
    </BaseDialog>
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import moment from 'moment';
import {
  getpartStocksList,
  getfindStorageCode,
  newBuild,
  edit,
  save,
  clearPartLocation,
  handletableOne,
  handletableTwo,
  monthStatement,
  clearStoragePositionAll
} from '@/api/part/inventoryManager/inventoryManager/index';
import { findAllRepair } from '@/api/repair/basicParameters';
import { getStorageList } from '@/api/part/common';
import addStock from './addStock.vue';
import { getBrandList } from '@/api/common/cars/masterDataCars';
import emitStock from './emitStock.vue';
import { confirmAction, notifyAction, arrayObjDeWeight } from '@/utils';
import { authority } from '@/utils/authMixin';

export default {
  name: 'zjinventoryIndex',
  props: {
    SfetchParams: {},
    rowData1: {
      type: Object,
      default: () => ({})
    }
  },
  components: {
    addStock,
    emitStock
  },
  mixins: [dictionary, authority],
  data() {
    // this.baseTable = null;
    return {
      fetchApi: getpartStocksList,
      fetchParams: { xhrAbort: true },
      addVisible: false,
      emitVisible: false,
      detailVisible: false,
      columns: this.createTable(),
      data: [],
      setEmitdata: {},
      setDetaildata: {},
      selectColumns: [],
      aaa: 1,
      questionList: [],
      // 打印标签数据
      labelPrintData: {
        partList: []
      },
      FrowData: {},
      selectedRow: [], // 选中的行项目
      tablePage: 1, // table页码
      selectPrintPartList: [], // 选中的打印项目
      pageSelectRows: [], // 当前页选中的行项(过滤取消勾选项用)
      formList: this.createFormList(),
      formList1: this.createFormList1()
    };
  },
  created() {
    // this.getBrandList();
  },
  watch: {
    rowData1: {
      handler(newVal, oldVal) {
        console.log('sn::', newVal);
        this.formList.forEach(x => {
          x.initialValue = newVal[x.fieldName];
        });
        this.formList1.forEach(x => {
          x.initialValue = newVal[x.fieldName];
        });
        this.FrowData = newVal;
      }
    },
    SfetchParams: {
      handler(newVal, oldVal) {
        console.log('sfp:::', newVal);
        this.changeHandle(newVal);
      }
    }
  },
  mounted() {
    window.asd = this;
    // this.baseTable = this.$refs.basetablewas.$refs.pageTable;
    this.formList.forEach(x => {
      x.initialValue = this.rowData1[x.fieldName];
    });
    this.formList1.forEach(x => {
      x.initialValue = this.rowData1[x.fieldName];
    });
    if (this.SfetchParams) {
      this.changeHandle(this.SfetchParams);
    }
  },
  methods: {
    // async getBrandList() {
    //   const res = await getBrandList();
    //   this.form.find(item => item.fieldName == 'brand').itemList = res.data.map(x => ({ text: x.brandName, value: x.brandCode }));
    //   this.columns.find(item => item.dataIndex == 'brand').itemList = res.data.map(x => ({ text: x.brandName, value: x.brandCode }));
    // },
    async clearLocation() {
      try {
        console.log('清空库位');
        await confirmAction();

        // clearStoragePositionAll
        let obj = this.selectColumns.map(x => {
          return {
            storageCode: x.storageCode,
            partNo: x.partNo
          };
        });
        const res = await clearStoragePositionAll(obj);

        // const res = await clearPartLocation(this.selectColumns[0].partNo, this.selectColumns[0].storageCode);
        if (res.resultCode === 200) {
          if (res.data.success.length) {
            notifyAction('操作成功！', 'success');
            // 刷新页面
            this.fetchParams = { ...this.fetchParams };
          }
          // this.$message({
          //   message: res.data.msg,
          //   type: 'success'
          // });
        }
      } catch (error) {
        console.log(error);
      }
    },
    createFormList() {
      return [
        {
          type: 'SELECT',
          label: '品牌',
          fieldName: 'brand',
          placeholder: '请选择',
          initialValue: '',
          disabled: true,
          itemList: [
            { text: 'BEIJING', value: 'beqi' },
            { text: 'ARCFOX', value: 'arc' }
          ]
        },
        {
          type: 'TEXT_AREA',
          label: '配件代码',
          fieldName: 'partNo',
          selfCols: 2,
          initialValue: '',
          disabled: true,
          placeholder: '请输入...'
          // rules: [{ required: true, message: '请输入配件代码', trigger: 'blur' }]
        },
        // {
        //   type: 'INPUT',
        //   label: '配件名称',
        //   fieldName: 'partDescription',
        //   disabled: true
        // },
        {
          type: 'INPUT',
          label: '配件名称',
          fieldName: 'partName',
          disabled: true,
          initialValue: '',
          selfCols: 2,
          placeholder: '请输入...'
        }
      ];
    },
    createFormList1() {
      return [
        {
          type: 'INPUT',
          label: '账面总库存',
          fieldName: 'stockQuantity',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '可用总库存',
          fieldName: 'usableQuantity',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '锁定数量',
          fieldName: 'lockedQuantity',
          disabled: true
        }
      ];
    },
    createTable() {
      return [
        {
          title: '操作',
          dataIndex: 'column-action',
          fixed: 'left',
          width: 100,
          render: (props, h) => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.emitFun(props.row)} disabled={this.isEmit(props)}>
                  编辑
                </el-button>
              </div>
              // <el-divider direction="vertical" />
              //  <el-button size="mini" type="text" onClick={() => this.delFun(props.row)} disabled={props.row.flg == 'A' ? false : true}>
              //     删除
              //   </el-button>
            );
          }
        },
        {
          title: '序号',
          dataIndex: 'index',
          sorter: true,
          width: 70,
          render: props => {
            return <span>{props.row.$index + 1}</span>;
          }
        },
        {
          title: '仓库名称',
          dataIndex: 'storageName',
          // width: 110,
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true,
          render: props => {
            return <span>{props.row.storageName}</span>;
          }
        },
        {
          title: '库位代码',
          dataIndex: 'storagePositionCode',
          sorter: true,
          // width: 110,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true,
          render: props => {
            return <span>{props.row.storagePositionCode}</span>;
          }
        },
        {
          title: '可用库存',
          dataIndex: 'useableStock',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2,
          showOverflowTooltip: true,
          width: 110
          // render: props => {
          //   return <span>{props.row.useableStock}</span>;
          // }
        },
        {
          title: '账面库存',
          dataIndex: 'stockQuantity',
          sorter: true,
          filter: true,
          precision: 2,
          showOverflowTooltip: true,
          filterType: 'number',
          width: 110
          // render: props => {
          //   return <span>{props.row.stockQuantity}</span>;
          // }
        },
        {
          title: '锁定数量',
          dataIndex: 'reservedQuantity',
          sorter: true,
          filter: true,
          precision: 2,
          // showOverflowTooltip: true,
          filterType: 'number',
          width: 110
          // render: props => {
          //   return <span>{props.row.lockedQuantity}</span>;
          // }
        },
        // {
        //   title: '最小包装数量',
        //   dataIndex: 'packageLiaght',
        //   sorter: true,
        //   filter: true,
        //   showOverflowTooltip: true,
        //   filterType: 'input'
        //   // render: props => {
        //   //   return <span>{props.row.stockQuantity}</span>;
        //   // }
        // },
        // {
        //   title: '建议销售价',
        //   dataIndex: 'notTaxInstructPrice',
        //   sorter: true,
        //   filter: true,
        //   render: props => {
        //     return <span>{props.row.notTaxInstructPrice}</span>;
        //   }
        // },
        // {
        //   title: '含税出库单价',
        //   // title: '出库单价',
        //   dataIndex: 'costOutPrice',
        //   sorter: true,
        //   filter: true,
        //   precision: 2,
        //   filterType: 'number'
        //   // render: props => {
        //   //   return <span>{props.row.costOutPrice}</span>;
        //   // }
        // },
        {
          title: '含税成本单价',
          dataIndex: 'costPrice',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number'
          // render: props => {
          //   return <span>{props.row.costPrice}</span>;
          // }
        },
        {
          title: '含税成本金额',
          dataIndex: 'costAmount',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2
          // render: props => {
          //   return <span>{props.row.costAmount}</span>;
          // }
        },
        {
          title: '最大库存',
          dataIndex: 'maxStock',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2
          // render: props => {
          //   return <span>{props.row.maxStock}</span>;
          // }
        },
        {
          title: '安全库存',
          dataIndex: 'safeStock',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2
          // render: props => {
          //   return <span>{props.row.safeStock}</span>;
          // }
        },
        {
          title: '最小库存',
          dataIndex: 'minStock',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2
          // render: props => {
          //   return <span>{props.row.minStock}</span>;
          // }
        },
        {
          title: '呆滞天数',
          dataIndex: 'sluggishDays',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2
          // render: props => {
          //   return <span>{props.row.minStock}</span>;
          // }
        },
        {
          title: '是否呆滞件',
          dataIndex: 'isSluggish',
          sorter: true,
          filter: true,
          filterType: 'input'
          // render: props => {
          //   return <span>{props.row.minStock}</span>;
          // }
        },
        {
          title: '最新入库日期',
          dataIndex: 'lastStockIn',
          sorter: true,
          filter: true,
          filterType: 'date-range'
          // render: props => {
          //   return <span>{props.row.lastStockIn}</span>;
          // }
          // dateFormat: 'yyyy-MM-dd'
        },
        {
          title: '最新出库日期',
          dataIndex: 'lastStockOut',
          sorter: true,
          filter: true,
          filterType: 'date-range'
          // render: props => {
          //   return <span>{props.row.lastStockOut}</span>;
          // }
        },
        {
          title: '状态',
          dataIndex: 'partStatus',
          sorter: true,
          filter: true,
          filterItems: [
            { text: '停用', value: 10041001 },
            { text: '启用', value: 10041002 }
          ],
          filterType: 'checkbox',
          dictItems: [
            { text: '停用', value: 10041001 },
            { text: '启用', value: 10041002 }
          ]
        }
      ];
    },
    // 执行月结
    async handleCun() {
      const resOne = await handletableOne();
      const resTwo = await handletableTwo();
      if (resOne.resultCode == 200 && resTwo.resultCode == 200) {
        this.$notify.success({ title: '提示信息', message: '执行月结成功!' });
      }
    },
    // async getStorage() {
    //   const res = await getStroageList();
    //   // let resdata = await findAllRepair();
    //   this.topFilterList.find(item => item.fieldName === 'STORAGE_CODE1').itemList = res.data.map(x => ({ text: x.STORAGE_NAME, value: x.STORAGE_CODE }));
    // },
    // 搜索
    changeHandle(val) {
      let searchData = _.cloneDeep(val);
      console.log(searchData.STORAGE_POSITION_CODE);

      if (searchData.STORAGE_POSITION_CODE) {
        if (searchData.STORAGE_POSITION_CODE.indexOf('_') != -1) {
          searchData.RESERVOIR_AREA = searchData.STORAGE_POSITION_CODE.slice(0, searchData.STORAGE_POSITION_CODE.indexOf('_'));
        } else {
          searchData.RESERVOIR_AREA = searchData.STORAGE_POSITION_CODE;
        }
        // searchData.STORAGE_POSITION_CODE = undefined;
        // } else {
        //   searchData.RESERVOIR_AREA = undefined;
      }
      console.log('搜索', searchData);
      searchData.xhrAbort = false;
      this.fetchParams = Object.assign({}, searchData);
      this.pageSelectRows = [];
    },
    collapseHandle() {
      this.$nextTick(() => {
        // this.$refs.basetablewas.EXECUTE_RESET_HEIGHT();
      });
    },
    // 双击显示
    tableDbclickFun(val) {
      console.log('打印了呀', val);
      this.form.forEach(x => {
        x.initialValue = val[x.fieldName];
      });
      if (val.foundDate != null && val.foundDate != '') {
        this.form.find(item => item.fieldName === 'foundDate').initialValue = moment(val.foundDate).format('YYYY-MM-DD');
        // this.form[17].initialValue = moment(val.foundDate).format('YYYY-MM-DD');
      }
      let partStatus = val.partStatus == 10041001 ? '是' : '否';
      this.form.find(item => item.fieldName === 'partStatus').initialValue = partStatus;
      // this.form[18].initialValue = partStatus;
    },
    formchangeFun(val) {},
    // table数据变化
    tablechangeFun(val) {
      if (val.length > 0) {
        console.log('tablechangeFunval', val);
        val.forEach(item => (item.partNoPosCode = item.partNo + item.storagePositionCode)); // 将配件代码及库位代码拼接(作为行项唯一标识)
        this.questionList = val;
        this.selectedRow = val.filter(item => !!this.selectPrintPartList.find(x => x.partNoPosCode == item.partNoPosCode));
        console.log(this.selectedRow, '页面数据变化重新赋值选中行项');
      }
    },
    addFun() {
      this.addVisible = true;
    },
    emitFun(data) {
      console.log('打压', data);
      this.setEmitdata = data;
      this.emitVisible = true;
    },
    detailFun(data) {
      this.setDetaildata = data;
      this.detailVisible = true;
      // this.selectColumns[0]=data;
    },
    delFun(data) {
      // this.baseTable.EXECUTE_DELETE([data]);
    },
    closeHandle(val) {
      // 关闭
      this.addVisible = false;
    },
    addChange(val) {
      // 添加成功
      console.log(1123);
      this.addVisible = false;
      // 刷新
      this.fetchParams = { ...this.fetchParams };
      this.columns = [...this.columns];
    },
    emitChange(val, index) {
      console.log(val, 'table值');
      console.log(index, 'index');
      this.emitVisible = false;
      this.fetchParams = { ...this.fetchParams };
      //  this.selectColumns[0].storageName='11110';
    },
    emitCloseHandle() {
      this.emitVisible = false;
    },
    detailCloseHandle() {
      this.detailVisible = false;
    },

    saveDataFun() {
      // console.log(this.aaa)
      this.selectColumns[0].partStatus = this.selectColumns[0].partStatus == '10041002' ? '10041001' : '10041002';
      console.log(this.selectColumns[0].partStatus);
      // 修改按钮
      this.aaa = this.aaa == 1 ? 0 : 1;
    },
    async saveDataFuns() {
      this.$confirm('是否确认保存?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      });
      // this.
      let obj = { dmstable: this.questionList };
      obj = JSON.parse(JSON.stringify(obj));
      let res = await save(obj);
      console.log('保存了', res);
    },
    isEmit(data) {
      return false;
    },
    isDetail(data) {
      return false;
    },
    // isDel(data) { }
    // 点击月结
    async handleMonthStatement() {
      let res = await monthStatement();
    },
    // 打印标签
    // handlePrintLabel() {
    //   if (!this.selectPrintPartList.length) {
    //     notifyAction('请选择需要打印的配件', 'warning');
    //   } else {
    //     confirmAction(`选中的配件${this.selectPrintPartList.map(item => item.partNo).join(',')}是否确认打印？`, 'warning')
    //       .then(e => {
    //         let printData = this.selectPrintPartList.map(item => ({
    //           partNo: item.partNo,
    //           partName: item.partName,
    //           storageInfo: item.storageCode,
    //           storageArea: item.storagePositionCode.split('_')[0],
    //           storagePosition: item.storagePositionCode.split('_')[1] || ''
    //         }));
    //         this.labelPrintData.partList = printData;
    //         // this.$refs.print.EXCUTE_PRINT();
    //         // 打印清空选中的配件及选中的行项
    //         this.selectPrintPartList = [];
    //         // this.$refs.basetablewas.DO_REFRESH(false);
    //       })
    //       .catch(err => {});
    //   }
    // },
    new() {
      this.data = [];
    },
    // table页码变化
    handleTablePageChange(e) {
      this.tablePage = e.pageNum;
      this.pageSelectRows = [];
    },
    // table行项选中变化
    handleTableSelectChange(e) {
      this.selectColumns = e;

      // 跨页跨搜索逻辑
      let deleteRows = this.pageSelectRows.filter(item => !e.find(x => x.partNo == item.partNo)); // 需要从打印列表中删除的行项（取消选择的行项）
      this.pageSelectRows = e;
      console.log(deleteRows, '删除的行项');
      this.selectPrintPartList = this.selectPrintPartList.filter(item => !deleteRows.find(x => x.partNo == item.partNo)); // 删除取消勾选的行项

      let totalPartList = [...this.selectPrintPartList, ...e];
      this.selectPrintPartList = arrayObjDeWeight(totalPartList, 'partNoPosCode');
      console.log(this.selectPrintPartList, '行项选中变化');
    }
  }
};
</script>

<style scoped lang="less"></style>
